<template>
	<view>
		<zmm-watermark :watermark="userStore.watermark" v-if="userStore.watermark"></zmm-watermark>
		<!--导航栏-->
		<pageLayout
			:barTitle="title"
			:isSearchNull="isSearchNull"
			:isOpen="isOpen"
			@rightClick="clickSearch">
		</pageLayout>
		<!--查询弹窗-->
		<up-popup :z-index="90" :show="isOpen" @close="closeSearch" mode="top">
			<view @touchmove.stop.prevent>
			<scroll-view class="search" scroll-y="true" @touchmove.stop>
				<view class="search-form">
					<uni-forms ref="searchRef" :modelValue="searchModel" label-width="160rpx">
						<uni-forms-item label="客户姓名">
							<uni-easyinput v-model="searchModel.customerName" placeholder="请输入客户姓名" />
						</uni-forms-item>
						<uni-forms-item label="联系电话">
							<uni-easyinput v-model="searchModel.phone" placeholder="请输入联系电话" />
						</uni-forms-item>
						<uni-forms-item label="门店名称">
							<uni-easyinput v-model="searchModel.storeName" placeholder="请输入门店名称" />
						</uni-forms-item>
						<uni-forms-item label="线索等级">
							<uni-data-select
								v-model="searchModel.level"
								placeholder="请选择线索等级"
								:localdata="customerClueLevelList"></uni-data-select>
						</uni-forms-item>
						<uni-forms-item label="线索状态">
							<uni-data-select
								v-model="searchModel.status"
								placeholder="请选择线索状态"
								:localdata="salesmanClueStatusList"></uni-data-select>
						</uni-forms-item>
						<uni-forms-item label="是否公海">
							<view class="search-form-checkbox main-flex">
								<uni-data-checkbox v-model="searchModel.isPublic" :localdata="salesmanClueIsPublicList" />
							</view>
						</uni-forms-item>
						<uni-forms-item label="有无电话">
						  <view class="search-form-checkbox main-flex">
						  	<uni-data-checkbox v-model="searchModel.isPhone" :localdata="[{ value: 1, text: '有'},{ value: 0, text: '无'}]" />
						  </view>
						</uni-forms-item>
						<uni-forms-item label="销售姓名">
							<uni-easyinput v-model="searchModel.relationSalesmanName" placeholder="请输入销售姓名" />
						</uni-forms-item>
						<uni-forms-item label="开始时间">
							<uni-datetime-picker type="datetime" placeholder="请选择开始时间" v-model="searchModel.startTime"/>
						</uni-forms-item>
						<uni-forms-item label="结束时间">
							<uni-datetime-picker type="datetime" placeholder="请选择结束时间" v-model="searchModel.endTime"/>
						</uni-forms-item>
						<uni-forms-item label=" ">
							<up-checkbox
									:customStyle="{marginBottom: '8px'}"
									label="附近一公里商户"
									name="nearby"
									usedAlone
									v-model:checked="searchModel.nearby">
							</up-checkbox>
						</uni-forms-item>
					</uni-forms>
					<view class="search-footer main-flex">
						<up-button
							class="search-footer-item"
							text="搜索"
							type="primary"
							@click="searchSubmit"
							icon="search"></up-button>
						<up-button
							class="search-footer-item"
							@click="resetSubmit"
							text="重置"></up-button>
					</view>
				</view>
			</scroll-view>
			</view>
		</up-popup>
		<view class="content">
			<!--操作-->
			<view class="operate main-flex">
				<view class="operate-item" v-if="checkPermi(['zhouyz:salesmanClue:add'])">
					<up-button
						class="operate-btn main-flex"
						size="mini"
						type="primary"
						@click="add()">
						<uni-icons class="operate-btn-icon" type="plusempty" size="28rpx" color="#ffffff"></uni-icons>
						<view class="operate-btn-text">添加</view>
					</up-button>
				</view>
				<view class="operate-item" style="margin-left: auto;">
					<up-button
						class="operate-btn main-flex"
						size="mini"
						type="primary"
						@click="goMap">
						<uni-icons class="operate-btn-icon" type="location" size="28rpx" color="#ffffff"></uni-icons>
						<view class="operate-btn-text">商户地图</view>
					</up-button>
				</view>
			</view>
			<!--内容-->
			<view class="table">
				<ty-table
					:data="tableList"
					:columns="columns"
					:sortable="true"
					@row-click="rowClick"
					:cellClassName="() => 'table-cell'"
					:headerCellClassName="() => 'table-cell'"
					:rowClassName="() => 'table-row'"
					stripe
					:isOperateBtn="(row) => {
						return checkPermi(['zhouyz:clueFollowRecord:add', 'zhouyz:salesmanClue:edit' ,'zhouyz:salesmanClue:remove'])
					}"
					border>
					<template v-slot:left="{ row }">
						<view class="table-td-cell">
							<view class="table-td-row">
								姓名：
								<text class="table-td-text">{{row.customerName}}</text></view>
							<view class="table-td-row">
								电话：
								<text class="table-td-text">{{row.phone == '18888888888' ? '无' : row.phone}}</text></view>
							<view class="table-td-row">
								等级：
								<text class="table-td-text">{{arrText(customerClueLevelList, row.level)}}</text></view>
							<view class="table-td-row">
								区域：
								<uni-tag size="small" :text="arrText(setStore.allProvinceList, row.regionCode)" />
							</view>
							<!-- <view class="table-td-row">
								转化订单：
								<text class="table-td-text">{{row.translationOrderNumber}}</text></view>
							<view class="table-td-row">
								关联销售：
								<text class="table-td-text"></text></view> -->
						</view>
					</template>
					<template v-slot:center="{ row }">
						<view class="table-td-cell">
							<view class="table-td-row">
								名称：
								<text class="table-td-text">{{row.storeName}}</text></view>
							<view class="table-td-row">
								地址：
								<text class="table-td-text">{{row.addr}}</text></view>
							<view class="table-td-row">
								地址详情：
								<text class="table-td-text">{{row.addrDetail}}</text></view>
						</view>
					</template>
					<template v-slot:right="{ row }">
						<view class="table-td-cell">
							<view class="table-td-row">
								是否公海：
								<uni-tag size="small" :type="row.isPublic == 0 ? 'success' : ''" :text="arrText(salesmanClueIsPublicList, row.isPublic)" /></view>
							<view class="table-td-row">
								拜访人：
								<text class="table-td-text">{{row.createName}}</text></view>
							<view class="table-td-row">
								时间：
								<text class="table-td-text">{{row.createTime}}</text></view>
							<view class="table-td-row">
								状态：
								<uni-tag size="small" :type="row.status == 1 ? 'success' : ''" :text="arrText(salesmanClueStatusList, row.status)" /></view>
						</view>
					</template>
					<template v-slot:operate="{ row }">
						<view class="table-td-operate table-cell table-td-row main-flex">
							<view class="table-operate-btn main-flex" v-if="checkPermi(['zhouyz:clueFollowRecord:list'])">
								<up-button
									size="mini"
									type="primary"
									@click.stop="clueFollowRecordList(row.id)">
									<uni-icons class="table-operate-btn-icon" type="auth" size="24rpx" color="#ffffff"></uni-icons>
									<view class="table-operate-btn-text">拜访日志</view>
								</up-button>
							</view>
							<view class="table-operate-btn main-flex" v-if="checkPermi(['zhouyz:clueFollowRecord:add'])">
								<up-button
									size="mini"
									type="primary"
									@click.stop="addClueFollowRecord(row.id)">
									<uni-icons class="table-operate-btn-icon" type="auth" size="24rpx" color="#ffffff"></uni-icons>
									<view class="table-operate-btn-text">拜访跟进</view>
								</up-button>
							</view>
							<view class="table-operate-btn main-flex" v-if="checkPermi(['zhouyz:salesmanClue:edit'])">
								<up-button
									size="mini"
									type="primary"
									@click.stop="add(row.id)">
									<uni-icons class="table-operate-btn-icon" type="compose" size="24rpx" color="#ffffff"></uni-icons>
									<view class="table-operate-btn-text">修改</view>
								</up-button>
							</view>
							<view class="table-operate-btn main-flex" v-if="checkPermi(['zhouyz:salesmanClue:remove'])">
								<up-button
									class="table-operate-btn main-flex"
									size="mini"
									type="error"
									@click.stop="deleteFun(row.id)">
									<uni-icons class="table-operate-btn-icon" type="trash" size="20rpx" color="#ffffff"></uni-icons>
									<view class="table-operate-btn-text">删除</view>
								</up-button>
							</view>
						</view>
					</template>
					<template v-slot:empty>
						<view class="table-empty">
							<up-empty mode="data"/>
						</view>
					</template>
				</ty-table>
			</view>
			<!--分页-->
			<view class="pagination" v-show="total > 0">
				<ty-pagination
					:total="total"
					:pageSize="pageSize"
					:currentPage="pageNum"
					:pageSizes="[10, 20, 30, 50]"
					mode="simple"
					layout="first,prev,page,next,last"
					@sizeChange="sizeChange"
					@change="pageChange">
				</ty-pagination>
			</view>
		</view>
		
	</view>
</template>

<script setup>
import { onLoad, onPullDownRefresh } from '@dcloudio/uni-app';
import { computed, onMounted, ref, getCurrentInstance, watch } from 'vue'
import { tab, auth, modal } from "@/plugins"
import { getTitle } from "@/utils/getter"
import { checkPermi, checkRole, checkOnlyPermi, checkOnlyRole } from "@/utils/permission"
import { allProvince } from "@/api/erp_api/region"
import { customerClueLevel } from "@/api/system/dict/data"
import { salesmanClue, salesmanClueDel } from "@/api/erp_api/sale"
import { isObjectEmptySimple, copyText, arrText, getUserLocation, getRecentDays } from '@/utils/ty.js'
import useUserStore from '@/store/modules/user'
import useSetStore from '@/store/modules/set'
import { salesmanClueStatusList, salesmanClueIsPublicList } from '@/utils/config.js'
import { onShow } from '@dcloudio/uni-app';
import { timeFormat } from 'uview-plus'

	const userStore = useUserStore()
	const setStore = useSetStore()
	const { proxy } = getCurrentInstance()
	const platform = uni.getSystemInfoSync().platform
	// 标题设置
	const title = ref('')
	const userId = ref('')
	onLoad((option) => {
		getLocationFun()
		userId.value = option?.userId || ''
		title.value = getTitle(userStore.menu)
		uni.setNavigationBarTitle({
			title: title.value 
		})
		uni.$on('refreshList', () => {
			getList()
		})
	})
	
	onShow(() => {
	})
	
	// 线索等级
	const customerClueLevelList = ref([])
	const getCustomerClueLevel = () => {
		return customerClueLevel().then(res => {
			customerClueLevelList.value = res.data.map(item => {
				return {
					...item,
					value: item.dictValue,
					text: item.dictLabel
				}
			}) || []
		})
	}
	
	const changePublic = (e) => {
		if (checkOnlyRole(['sales_man'])) {
			searchModel.value.relationSalesmanName = ''
		}
	}
	
	// 搜索相关
	const isSearchNull = ref(true)
	const isOpen =  ref(false)
	const clickSearch = (val) => {
		isOpen.value = val
	}
	const closeSearch = (val) => {
		isOpen.value = false
	}
	// 确认搜索
	const searchRef = ref(null)
	const searchModel = ref({
		customerName: '',
		phone: '',
		level: '',
		storeName: '',
		relationSalesmanName: '',
		isPublic: '',
		isPhone: '',
		status: '',
		startTime: '',
		endTime: '',
		nearby: false
	})
	const lat = ref('')
	const lng = ref('')
	const searchSubmit = () => {
		pageNum.value = 1
		tableList.value = []
		isOpen.value = false
		searchFirst()
	}
	// 重置搜索
	const resetSubmit = () => {
		// searchRef.value.resetFields()
		searchModel.value = {
			customerName: '',
			phone: '',
			level: '',
			storeName: '',
			relationSalesmanName: '',
			isPublic: '',
			isPhone: '',
			status: '',
			startTime: '',
			endTime: '',
			nearby: false
		}
		// setTime()
		isSearchNull.value = true
		isOpen.value = false
		searchFirst()
	}
	
	const setTime = () => {
		searchModel.value.startTime = `${getRecentDays(7)} 00:00:00`
		searchModel.value.endTime = `${timeFormat(new Date(), 'yyyy-mm-dd')} 23:59:59`
	}
	
	// 数据查询
	const pageNum = ref(1)
	const pageSize = ref(10)
	const total = ref(0)
	const tableList = ref([])
	const isLoading = ref(false)
	
	// 表格头部
	const columns = ref([
		{ title: '客户信息', key: 'left' },
		{ title: '门店信息', key: 'center' },
		{ title: '其他信息', key: 'right' }
	])
	
	// 从第一页查询
	const searchFirst = () => {
		pageNum.value = 1
		tableList.value = []
		isSearchNull.value = isObjectEmptySimple(searchModel.value)
		getList()
	}
	//页数切换
	const pageChange = (page) => {
		pageNum.value = page
		getList()
	}
	//每页条数切换
	const sizeChange = (size) => {
		pageSize.value = size
		getList()
	}
	
	const getList = async () => {
		const params = {
			pageNum: pageNum.value,
			pageSize: pageSize.value
		}
		if (searchModel.value.customerName) {
			params.customerName = searchModel.value.customerName
		}
		if (searchModel.value.phone) {
			params.phone = searchModel.value.phone
		}
		if (searchModel.value.level) {
			params.level = searchModel.value.level
		}
		if (searchModel.value.storeName) {
			params.storeName = searchModel.value.storeName
		}
		if (searchModel.value.relationSalesmanName) {
			params.relationSalesmanName = searchModel.value.relationSalesmanName
		}
		if (searchModel.value.isPublic || searchModel.value.isPublic === 0) {
			params.isPublic = searchModel.value.isPublic
		}
		if (searchModel.value.status || searchModel.value.status === 0) {
			params.status = searchModel.value.status
		}
		if (userId.value) {
			params.createId = userId.value
		}
		if (searchModel.value.startTime) {
			params.startTime = searchModel.value.startTime
		}
		if (searchModel.value.endTime) {
			params.endTime = searchModel.value.endTime
		}
		if (searchModel.value.isPhone === 0) {
			params.phone = '18888888888'
		}
		if (searchModel.value.nearby) {
			if (lng.value) {
				params.lng = lng.value
			}
			if (lat.value) {
				params.lat = lat.value
			}
		}
		setStore.setSalesmanClueParams({
			...params,
			nearby: searchModel.value.nearby
		})
		isLoading.value = true
		uni.showLoading({
			title: '数据加载中...'
		})
		salesmanClue(params).then(res => {
			tableList.value = res.rows || []
			total.value = res.total
			isLoading.value = false
			uni.hideLoading()
			uni.stopPullDownRefresh()
    }).catch(() => {
			isLoading.value = false
			uni.hideLoading()
		})
	}
	
	// 详情
	const rowClick = (row) => {
		uni.navigateTo({
			url: `/pages/sale/salesmanClueDetail?id=${row.id}`
		})
	}
	
	//编辑
	const add = (id) => {
		uni.navigateTo({
			url: id ? `/pages/sale/salesmanClueAdd?id=${id}` : '/pages/sale/salesmanClueAdd'
		})
	}
	
	//线索跟进
	const addClueFollowRecord = (id) => {
		uni.navigateTo({
			url: `/pages/sale/salesmanClueFollowAdd?clueId=${id}`
		})
	}
	// 拜访日志
	const clueFollowRecordList = (id) => {
		uni.navigateTo({
			url: `/pages/sale/salesmanClueFollow?clueId=${id}`
		})
	}
	
	//删除
	const deleteFun = (id) => {
		uni.showModal({
			title: '删除',
			content: `是否确认删除销售线索编号为"${id}"的数据项?`,
			success: function (res) {
				if (res.confirm) {
					deleteOne(id)
				}
			}
		})
	}
	const deleteOne = (id) => {
		salesmanClueDel({
			id
		}).then(res => {
			modal.showToast('删除成功')
			getList()
		}).catch((err) => {
			modal.showToast(err)
		})
	}
	
	// 下拉刷新
	onPullDownRefresh(() => {
		getList()
	})
	
	const getLocationFun = () => {
		getUserLocation().then(res => {
			// console.log(res)
			lng.value = res?.longitude || ''
			lat.value = res?.latitude || ''
		}).catch(err => {
			modal.msg('定位失败，是否打开定位。')
		})
	}
	const goMap = async () => {
		if (!setStore?.salesmanClueParams?.startTime) return modal.msg('请选择开始时间')
		if (!setStore?.salesmanClueParams?.endTime) return modal.msg('请选择结束时间')
		uni.navigateTo({
			url: `/pages/sale/salesmanClueMap?lng=${lng.value}&lat=${lat.value}`
		})
	}
	
	watch(() => lng.value, (nval, oval) => {
		// console.log(nval)
		if (nval) {
			searchFirst()
		}
	})
	watch(() => userStore.roles, (nval, oval) => {
		if (nval && nval.length > 0) {
			// setTime()
			searchFirst()
		}
	}, { immediate: true })
	
	onMounted(async () => {
		await getCustomerClueLevel()
		searchFirst()
	})
</script>

<style scoped lang="scss">
</style>
